import random
import time
import math

move_file_path = r"G:\tdma-projects\omnet-tdma-main\tdma\simulations\mymotion.movements"
num_hosts = 5
min_x, min_y, max_x, max_y = 100, 0, 600, 400
direction_change = 0.25  # 节点目标位置改变概率
run_rounds = 1
change_interval = 0.05
max_move_radius = 70


def generate_random_positions(num_nodes=3, min_x=0, min_y=0, max_x=600, max_y=400):
    positions = []
    for _ in range(num_nodes):
        x = random.randint(min_x, max_x - 1)
        y = random.randint(min_y, max_y - 1)
        positions.append((x, y))
    return positions


def generate_random_position(min_x=0, min_y=0, max_x=600, max_y=400):
    x = random.randint(min_x, max_x - 1)
    y = random.randint(min_y, max_y - 1)
    return x, y


def generate_random_position_in_circle(node_position, radius):
    x_center, y_center = node_position
    # 随机生成一个位于[0, 2π]范围内的角度
    angle = random.uniform(0, 2 * math.pi)

    # 随机生成一个位于[0, r]范围内的半径（这里不需要考虑负半径，因为我们只关心圆内点）
    r_random = random.uniform(0, radius)

    # 根据极坐标转换为笛卡尔坐标
    new_x = x_center + r_random * math.cos(angle)
    new_y = y_center + r_random * math.sin(angle)

    return int(new_x), int(new_y)  # 直接返回落在圆内的随机位置


def check_boundary(position, min_x, min_y, max_x, max_y):
    x, y = position
    return min_x <= x <= max_x and min_y <= y <= max_y


def update_node_positions(file_path):
    # 获取初始位置
    node_positions = generate_random_positions(num_hosts, min_x, min_y, max_x, max_y)
    global run_rounds
    while True:

        # 每隔500毫秒更新一次节点位置
        time.sleep(change_interval)

        # 重写位置文件
        with open(file_path, 'w') as file:
            for node_id, (x, y) in enumerate(node_positions):
                line = f"{node_id} {x} {y}\n"
                file.write(line)
                print(f"node {node_id} is at {x}, {y}")
            print("#" * 25, run_rounds, "#" * 25)
            run_rounds += 1

        # 更新节点的位置
        for node_id, position in enumerate(node_positions):
            # 每个节点一轮有概率改变目标位置
            if random.random() < direction_change:
                print(f"node {node_id} changed direction, new position is {position}")
                new_pos = generate_random_position_in_circle(position, max_move_radius)
                while not check_boundary(new_pos, min_x, min_y, max_x, max_y):
                    new_pos = generate_random_position_in_circle(position, max_move_radius)
                node_positions[node_id] = new_pos  # 更新节点的新位置


if __name__ == '__main__':
    # 调用函数开始更新节点位置
    update_node_positions(move_file_path)
